//
//  PictureSelectorViewController.swift
//  SinaWebo
//
//  Created by mis on 16/3/24.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let column: CGFloat = 4
private let pictureCellMaigin: CGFloat = 10

private let maxImageCount = 3

class PictureSelectorViewController: UICollectionViewController {

    lazy var imageList = [UIImage]()
    
    init() {
        let layout = UICollectionViewFlowLayout()
        let w = (screenW - (column + 1) * pictureCellMaigin ) / column
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = pictureCellMaigin
        layout.minimumLineSpacing = pictureCellMaigin
        layout.sectionInset = UIEdgeInsets(top: pictureCellMaigin, left: pictureCellMaigin, bottom: 0, right: pictureCellMaigin)
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = (imageList.count == maxImageCount) ? 0 : 1
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        cell.selectorCellDelegate = self
        if indexPath.item == imageList.count {
            cell.image = nil
        }else {
            cell.image = imageList[indexPath.item]
        }
        return cell
    }
}

@objc protocol PictureSelectorDelegate: NSObjectProtocol {
    optional func userWillAddPicture(cell: PictureSelectorCell)
    optional func userWillDeletePicture(cell: PictureSelectorCell)
}

extension PictureSelectorViewController: PictureSelectorDelegate {
    func userWillAddPicture(cell: PictureSelectorCell) {
        if cell.image != nil {
            return
        }
        let picker = UIImagePickerController()
        picker.sourceType = .PhotoLibrary
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func userWillDeletePicture(cell: PictureSelectorCell) {
        let indexPath = collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex(indexPath!.item)
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            cell.alpha = 0
            }) { (_) -> Void in
                cell.alpha = 1
                self.collectionView?.reloadData()
        }
    }
}

extension PictureSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageList.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

class PictureSelectorCell: UICollectionViewCell {
    
    weak var selectorCellDelegate: PictureSelectorDelegate?
    
    @objc private func addBtnDidClick() {
        selectorCellDelegate?.userWillAddPicture?(self)
    }
    
    @objc private func deleteBtnClick() {
        selectorCellDelegate?.userWillDeletePicture?(self)
    }
    
    var image: UIImage? {
        didSet {
            deleteBtn.hidden = (image == nil)
            if image != nil {
                addBtn.setBackgroundImage(image, forState: .Normal)
            }else {
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnClick", forControlEvents: .TouchUpInside)
    }
    
    private lazy var addBtn: UIButton = UIButton(title: nil
        , backImage: "compose_pic_add", color: nil)
    private lazy var deleteBtn: UIButton = UIButton(title: nil
        , backImage: "compose_photo_close", color: nil)
}
